package com.icepeach.icepeachhomeback.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.icepeach.icepeachhomeback.entity.User;
import com.icepeach.icepeachhomeback.service.UserService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
@Component
public class TokenUtils {

    public static UserService staticUserService;

    @Resource
    public UserService userService;

    @PostConstruct
    public void setUserService(){
        staticUserService=userService;
    }

    public static String getToken(String id,String password) {
        String token="";
        token= JWT.create().withAudience(id) // 将 user id 保存到 token 里面
                .withExpiresAt(DateUtil.offsetHour(new Date(),2)) //两小时后token过期
                .sign(Algorithm.HMAC256(password)); // 以 password 作为 token 的密钥
        return token;
    }


    public static User getCurrrentUser(){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        if(StrUtil.isNotBlank(token)){
            String userId= JWT.decode(token).getAudience().get(0);
            return staticUserService.getById(userId);
        }
        }catch (Exception e){
            return null;

        }
        return null;
    }
}
